package woaini.wind.bot.core.dispatcher.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import woaini.wind.bot.core.chat.ChatEvent;
import woaini.wind.bot.core.dispatcher.IBotInterceptor;
import woaini.wind.bot.core.dispatcher.impl.CmdInterceptor;
import woaini.wind.bot.core.event.message.impl.GroupMessageEvent;
import woaini.wind.bot.core.event.message.impl.PrivateMessageEvent;
import woaini.wind.bot.core.session.Session;

@Component
@Slf4j
@RequiredArgsConstructor
public class ChatInterceptor implements IBotInterceptor {

  private final ApplicationEventPublisher eventPublisher;

  @Override
  public boolean preDispatch(Session session) {

    boolean privateEvent = session.getEvent() instanceof PrivateMessageEvent || session.getEvent() instanceof GroupMessageEvent;
    //不是这些消息直接返回了
    if (!privateEvent) {
      return false;
    }
    //私聊消息只有管理员可以触发
    if (session.getEvent() instanceof PrivateMessageEvent){
      boolean contains = session.getAuthCmds().contains("*");
      if (!contains) {
        return false;
      }
    }
    //群里消息需要@
    if (session.getEvent() instanceof GroupMessageEvent groupMessageEvent){
      return groupMessageEvent.getMessage().isAt(session.getBot().getSelfId());
    }
    return true;
  }

  @Override
  public boolean dispatch(Session session) {
    eventPublisher.publishEvent(new ChatEvent(this, session));
    return IBotInterceptor.super.dispatch(session);
  }

  @Override
  public int order() {
    return CmdInterceptor.ORDER + 1;
  }
}
